//
//  BussinessMapViewController.m
//  联付商圈
//
//  Created by 韩佳睿 on 2017/8/12.
//  Copyright © 2017年 lianfu. All rights reserved.
//

#import "BussinessMapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "Pin.h"

@interface BussinessMapViewController ()<MKMapViewDelegate, CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) Pin *pin;

@end

@implementation BussinessMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"店铺地图定位";
    
    //设置MapView的委托为自己
    self.mapView.delegate = self;
    
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [CLLocationManager new];
        self.locationManager.delegate = self;
    
        [self.locationManager startUpdatingLocation];
    }
    
    //标注自身位置
    [self.mapView setShowsUserLocation:YES];
    
    UITapGestureRecognizer *mTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPress:)];
    [self.mapView addGestureRecognizer:mTap];
}

- (void)tapPress:(UIGestureRecognizer*)gestureRecognizer
{
    [self.mapView removeAnnotation:_pin];
    
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView ];
    CLLocationCoordinate2D touchMapCoordinate =
    [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView ];
    
    _pin = [[Pin alloc] initWithCoordinate:touchMapCoordinate andTitle:nil];
    [self.mapView addAnnotation:_pin];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {

    CLLocation *location = [locations firstObject];
    //设置地图显示经纬度的位置
    MKCoordinateRegion region = MKCoordinateRegionMake(location.coordinate, MKCoordinateSpanMake(0.5, 0.5));
    [self.mapView setRegion:region animated:YES];
    
    [self.locationManager stopUpdatingLocation];
}

- (IBAction)saveBtnAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
